package com.cms.controller.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import com.cms.entity.Article;
import com.cms.entity.PageBean;
import com.cms.service.ArticleService;
import com.cms.service.impl.InitComponet;
import com.cms.util.DateJsonValueProcessor;
import com.cms.util.ResponseUtil;
import com.cms.util.StringUtil;

/**
 * 文章后台管理Controller层
 * @author user
 *
 */
@Controller
@RequestMapping("/admin/article")
public class ArticleAdminController {

	@Resource
	private ArticleService articleService;
	@Resource
	private InitComponet initComponent;

	/**
	 * 添加或者修改文章信息
	 * @param article
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(@RequestParam("slideImageFile") MultipartFile slideImageFile, 
			Article article,HttpServletResponse response,HttpServletRequest request)throws Exception{
		
		int resultTotal=0; // 操作的记录条数		
		
		if(!slideImageFile.isEmpty()){
			
			String filePath=request.getServletContext().getRealPath("/");
			Date date=new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
			
			String imageName=sdf.format(date)+"."+slideImageFile.getOriginalFilename().split("\\.")[1];
			
			slideImageFile.transferTo(new File(filePath+"/static/userImages/"+imageName));
			
			System.out.println(new File(filePath+"/static/userImages/"));
			
			article.setSlideImage(imageName);	
		
		}
		if(article.getId()==null){ // 添加
			article.setPublishDate(new Date());
			resultTotal=articleService.add(article);
			StringBuffer result=new StringBuffer();
			if(resultTotal>0){
				result.append("<script language='javascript'>alert('添加成功');parent.location.reload();</script>");
				initComponent.refreshSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext());
			}else{
				result.append("<script language='javascript'>alert('添加失败，请联系管理员');</script>");
			}
			ResponseUtil.write(response, result);
		}else{ // 修改
			resultTotal=articleService.update(article);			
			JSONObject result=new JSONObject();
			if(resultTotal>0){
				result.put("success", true);				
				initComponent.refreshSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext());
			}else{
				result.put("success", false);
			}
			ResponseUtil.write(response, result);
		}		
		return null;
	}
	
	
	/**
	 * 根据条件分页查询文章信息
	 * @param page
	 * @param rows
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public String list(Article s_article,@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String pageSize,
			HttpServletResponse response)throws Exception{
		//数据表格组件在第一次请求就会带参数过来page=1,rows=10
		System.out.println("page="+page+",rows="+pageSize);
		//这个分页对象我们是简化了的，实质就是为了求limit字句中的start，要跳过多少条记录
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(pageSize));
		//下面三居为select查询构建limit字句
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		
		map.put("title", StringUtil.formatLike(s_article.getTitle()));
		
		
		//进行按分页查询
		List<Article> articleList=articleService.list(map);
		//不受map中封装的分页查询影响
		Long total=articleService.getTotal(map);
		//上面的分页数据集合我们通过下面的代码转换成如下格式
		//[{id:1,title:"fdsaf",artType:{typeName:"java爬虫",.....}},{},{}...]
		JSONObject result=new JSONObject();
		//把字段转换器注册到jsonConfig中
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		//将集合通过jsonarray转成json数组
		//[{id:1,title:"fdsaf",artType:{typeName:"java爬虫",.....}},{},{}...]
		JSONArray jsonArray=JSONArray.fromObject(articleList, jsonConfig);
		
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	
	@RequestMapping("/all")
	public String all(@RequestParam(value="type",required=true)String type, HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("type", type);
		Long l = articleService.getTotal(map);
		JSONObject jsonObject= new JSONObject();
		jsonObject.put("num", l);
		System.out.println(l);
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	
	/**
	 * 通过ID查找实体
	 * @param id
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findById")
	public String findById(@RequestParam(value="id")String id,HttpServletResponse response)throws Exception{
		
		Article article=articleService.findById(Integer.parseInt(id));
		JSONObject jsonObject=JSONObject.fromObject(article);
		System.out.println(jsonObject);
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	
	
	/**
	 * 删除文章信息
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 * ids="2,3,4"
	 */
	@RequestMapping("/delete") 
	public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		String []idsStr=ids.split(",");
		for(int i=0;i<idsStr.length;i++){
			articleService.delete(Integer.parseInt(idsStr[i]));
		}
		initComponent.refreshSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext());
		JSONObject result=new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}



	
	
	
	
}

